package com.example.userbehaviorprediction;

import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleAdapter;
import android.widget.Toast;


import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class frag2 extends Fragment implements View.OnClickListener,AdapterView.OnItemClickListener, AbsListView.OnScrollListener{

    private ImageView image;
    private SearchView svSearch;
    private boolean temp=true;  //
    View view2;

    private ListView dataListview;
    private List<Map<String, Object>> dataList;
    private ArrayList<AppInfo> appList = new ArrayList<AppInfo>();

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        List<PackageInfo> packages = getContext().getPackageManager().getInstalledPackages(PackageManager.GET_PERMISSIONS);
        for (int i = 0; i < packages.size(); i++) {
            PackageInfo packageInfo = packages.get(i);
            // 如果不是系统应用，则添加至appList
            if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
                //Log.e("psn:",packageInfo.packageName+i);
                AppInfo mAppInfo = new AppInfo();
                mAppInfo.setAppName(packageInfo.applicationInfo.loadLabel(getContext().getPackageManager()).toString());
                // Log.e("name:",mAppInfo.getAppName());
                mAppInfo.setPackageName(packageInfo.packageName);
                mAppInfo.setAppIcon(packageInfo.applicationInfo.loadIcon(getContext().getPackageManager()));
                appList.add(mAppInfo);
            }
        }

        Log.e("ps:","大小"+appList.size());
        for (int i = 0; i < appList.size(); i++)
            Log.e("ps:","包名"+appList.get(i).getPackageName());





        View view = inflater.inflate(R.layout.frag2,container,false);
        view2 = inflater.inflate(R.layout.data, null);

        initlist(view,inflater, container);

        init(view);

        return view;

    }

    public void onActivityCreated(@Nullable Bundle savedInstanceState) {


        super.onActivityCreated(savedInstanceState);
        svSearch = (SearchView) getActivity().findViewById(R.id.seach_view);
//        svSearch.setIconified(false);
//        svSearch.setIconifiedByDefault(false);
        //展开搜索框
        svSearch.onActionViewExpanded();
        svSearch.clearFocus();
        svSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override

            public boolean onQueryTextSubmit(String query) {
                int i;
                for (i = 0; i < appList.size(); i++) {
                    AppInfo mAppInfo=appList.get(i);
                    //Log.e("name:",mAppInfo.getAppName()+appList.size());
                    if(mAppInfo.getAppName().indexOf(query)!=-1){
                        //Log.e("name=:",mAppInfo.getAppName());
                        //mAppList.add(mAppInfo);
                        //name=mAppInfo.getAppName();
                        //flag=true;
                        query = mAppInfo.getPackageName();
                        //i=appList.size();
                        //icon = mAppInfo.getAppIcon();
                    }
                }


                Toast.makeText(getActivity(), "开始搜索app", Toast.LENGTH_SHORT).show();
                String sql = "select * from appUse where name like '%" +query+"%'";
                SimpleAdapter simpleAdapter = new SimpleAdapter(getActivity(), getData(sql), R.layout.data, new String[]{"icon","name", "firstTime","lastTime","totalTime","times"}, new int[]{R.id.icon,R.id.name, R.id.firstTime,R.id.lastTime,R.id.totalTime,R.id.times});
                dataListview.setAdapter(simpleAdapter);


                simpleAdapter.setViewBinder(new SimpleAdapter.ViewBinder() {
                    @Override
                    public boolean setViewValue(View view, Object data, String arg2) {
                        if(view instanceof ImageView && data instanceof Drawable){
                            ImageView iv = (ImageView)view;
                            iv.setImageDrawable((Drawable)data);
                            return true;
                        }else{
                            return false;
                        }
                    }
                });
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return false;
            }
        });


    }

    private void init(View view) {
        image = (ImageView) view.findViewById(R.id.haoyou_guanzhufensi);
        image.setOnClickListener(this);
    }


    private void initlist(View view,LayoutInflater inflater,ViewGroup container) {

        dataListview = (ListView) view.findViewById(R.id.haoyou_list);
        String sql = "select * from appUse";
        SimpleAdapter simpleAdapter = new SimpleAdapter(getActivity(), getData(sql), R.layout.data, new String[]{"icon","name", "firstTime","lastTime","totalTime","times"}, new int[]{R.id.icon,R.id.name, R.id.firstTime,R.id.lastTime,R.id.totalTime,R.id.times});
        dataListview.setAdapter(simpleAdapter);

        simpleAdapter.setViewBinder(new SimpleAdapter.ViewBinder() {
            @Override
            public boolean setViewValue(View view, Object data, String arg2) {
                if(view instanceof ImageView && data instanceof Drawable){
                    ImageView iv = (ImageView)view;
                    iv.setImageDrawable((Drawable)data);
                    return true;
                }else{
                    return false;
                }
            }
        });

        dataListview.setAdapter(simpleAdapter);

        dataListview.setOnItemClickListener(this);
        dataListview.setOnScrollListener(this);
    }

    private List<? extends Map<String, ?>> getData(String sql) {

        dataList = new ArrayList<Map<String, Object>>();

//        Map<String, Object> map1 = new HashMap<String, Object>();
//        map1.put("pic", R.mipmap.ic_launcher);
//        map1.put("text", "个人中心");
//        dataList.add(map1);
//
//        Map<String, Object> map2 = new HashMap<String, Object>();
//        map2.put("pic", R.mipmap.ic_launcher);
//        map2.put("text", "宝贝中心");
//        dataList.add(map2);
        SQLiteOpenHelper helper = MySqliteOpenHelper.getmInstance(getActivity());
        SQLiteDatabase readableDatabase = helper.getReadableDatabase();
        if (readableDatabase.isOpen()) {
            Cursor cursor = readableDatabase.rawQuery(sql, null);
            while(cursor.moveToNext()) {
                String name = cursor.getString(1);
                String firstTime = cursor.getString(2);
                String lastTime = cursor.getString(3);
                String totalTime = cursor.getString(4);
                int times = cursor.getInt(5);



                boolean flag = false;
                int i;
                for (i = 0; i < appList.size(); i++) {
                    AppInfo mAppInfo=appList.get(i);
                    //Log.e("name:",mAppInfo.getAppName()+appList.size());
                    if(mAppInfo.getPackageName().equals(name)){
                        //Log.e("name=:",mAppInfo.getAppName());
                        //mAppList.add(mAppInfo);
                        //name=mAppInfo.getAppName();
                        flag=true;
                        break;
                        //i=appList.size();
                        //icon = mAppInfo.getAppIcon();
                    }
                }
                Log.e("ps:","flag: "+flag);

                if (!flag) continue;
                AppInfo mAppInfo=appList.get(i);
                name = mAppInfo.getAppName();
                Log.e("ps:","我的包名"+name);
                Drawable icon =mAppInfo.getAppIcon();

                Map<String, Object> map = new HashMap<String, Object>();
                map.put("icon", icon);
                map.put("name", name);
                map.put("firstTime", firstTime);
                map.put("lastTime", lastTime);
                map.put("totalTime", totalTime);
                map.put("times", times);
                dataList.add(map);

            }
            cursor.close();
            readableDatabase.close();
        }



//        for (int i = 0; i < 20; i++) {
//            Map<String, Object> map = new HashMap<String, Object>();
//            map.put("name", "name");
//            map.put("firstTime", "firstTime");
//            map.put("lastTime", "lastTime");
//            map.put("totalTime", "totalTime");
//            map.put("times", "times");
//            dataList.add(map);
//        }
        return dataList;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.icon:
                Data();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        Toast.makeText(getActivity(), "别点，哥，点不进去的", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onScrollStateChanged(AbsListView absListView, int i) {

    }

    @Override
    public void onScroll(AbsListView absListView, int i, int i1, int i2) {

    }

    private void Data() {
        if(temp) {
            image.setSelected(temp);
            temp =false;
        }
        else{
            image.setSelected(temp);
            temp = true;
        }
    }
}

